import argparse
from pathlib import Path
from typing import List

from app.config import Config
from app import asr
from app.enhanced_llm import EnhancedDoubaoLLM
from app.enhanced_executor import EnhancedActionExecutor
from app.tts import SpeechFeedback
from app.orchestrator import DialogueOrchestrator
from app.logger import init_terminal_log_capture, log_event

# 初始化终端日志捕获（5MB轮转，秒级命名）
init_terminal_log_capture(max_bytes=5 * 1024 * 1024, flush_interval_sec=1.0)


def run_pipeline_from_text(text: str) -> None:
    llm = EnhancedDoubaoLLM()
    executor = EnhancedActionExecutor(llm=llm)
    speaker = SpeechFeedback()

    cleaned = asr.preprocess_text(text)
    actions = llm.parse_command(cleaned)
    # 按序执行并加入短延时，便于观察输入效果
    results = executor.execute_sequence(actions, delay=0.6)

    # Build feedback message
    for r in results:
        if r["action"] == "play_music":
            msg = (r.get("detail", "音乐播放已处理") if r["success"] else f"音乐播放失败：{r['detail']}")
            print(msg)
            speaker.speak(msg)
        elif r["action"] == "write_article":
            msg = (r.get("detail", "文章已生成并保存") if r["success"] else f"写作失败：{r['detail']}")
            print(msg)
            speaker.speak(msg)
        elif r["action"] == "file_op":
            msg = (r.get("detail", "文件操作已完成") if r["success"] else f"文件操作失败：{r['detail']}")
            print(msg)
            speaker.speak(msg)
        elif r["action"] == "app_control":
            msg = (r.get("detail", "应用操作已完成") if r["success"] else f"应用操作失败：{r['detail']}")
            print(msg)
            speaker.speak(msg)
        elif r["action"] == "system_control":
            msg = (r.get("detail", "系统设置已调整") if r["success"] else f"系统操作失败：{r['detail']}")
            print(msg)
            speaker.speak(msg)
        elif r["action"] == "web_search":
            msg = (r.get("detail", "已打开搜索页") if r["success"] else f"搜索失败：{r['detail']}")
            print(msg)
            speaker.speak(msg)
        elif r["action"] == "navigate":
            msg = (r.get("detail", "已打开目标页面") if r["success"] else f"导航失败：{r['detail']}")
            print(msg)
            speaker.speak(msg)
        elif r["action"] == "browser_click":
            msg = (r.get("detail", "已点击目标链接") if r["success"] else f"点击失败：{r['detail']}")
            print(msg)
            speaker.speak(msg)
        elif r["action"] == "computer_type":
            # 将输入文本内容也输出到终端与日志
            msg = r.get("detail") or ("输入文本成功" if r.get("success") else "输入失败，请检查焦点")
            print(msg)
            try:
                log_event("TYPE_TEXT_FEEDBACK", msg)
            except Exception:
                pass
            speaker.speak(msg)
        elif r["action"] == "needs_clarification":
            msg = r["detail"]
            print(msg)
            speaker.speak(msg)
        else:
            msg = r.get("detail") or f"未知动作: {r['action']}"
            print(msg)
            speaker.speak(msg)


def run_pipeline_from_mic(duration: float = 5.0) -> None:
    audio_path = asr.record_audio(Config.AUDIO_DIR / "user_input.wav", duration=duration)
    print(f"已录音：{audio_path}")
    text = asr.transcribe_with_whisper(audio_path)
    print(f"识别文本：{text}")
    run_pipeline_from_text(text)


def run_pipeline_dialog(text: str, auto_approve: None | bool = None, max_rounds: None | int = None) -> None:
    llm = EnhancedDoubaoLLM()
    executor = EnhancedActionExecutor(llm=llm)
    speaker = SpeechFeedback()
    orchestrator = DialogueOrchestrator(llm=llm, executor=executor, speaker=speaker, auto_approve=auto_approve, max_rounds=max_rounds)
    orchestrator.run_goal(text)


def main():
    parser = argparse.ArgumentParser(description="语音对话电脑控制 应用")
    parser.add_argument("--mode", choices=["mic", "text", "pet", "dialog"], default="text", help="输入模式：mic、text、pet或dialog")
    parser.add_argument("--text", type=str, default="播放《青花瓷》", help="当mode=text或dialog时的输入文本")
    parser.add_argument("--duration", type=float, default=5.0, help="当mode=mic时的录音秒数")
    # 新增：dialog 模式选项
    parser.add_argument("--rounds", type=int, default=None, help="当mode=dialog时的最大轮数，默认使用配置")
    parser.add_argument("--require-approval", action="store_true", help="当mode=dialog时启用手动审批（覆盖配置）")
    args = parser.parse_args()

    if args.mode == "mic":
        run_pipeline_from_mic(duration=args.duration)
    elif args.mode == "pet":
        from app.pet import run_pet
        run_pet()
    elif args.mode == "dialog":
        auto_approve = False if args.require_approval else None
        run_pipeline_dialog(args.text, auto_approve=auto_approve, max_rounds=args.rounds)
    else:
        run_pipeline_from_text(args.text)


if __name__ == "__main__":
    main()